<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class user extends CI_Controller {

    var $theme_data = array(
        'layout_main' => 'frontend/layout/home',
        'left' => 'frontend/include/left',
        'right' => 'frontend/include/right',
    );

    function __construct() {
        parent::__construct();
		$this->load->helper('module');
		$this->load->model('muser');
		$this->load->model('mcategory');
    }
	
	function index() {
		if (!$this->muser->checkLogin()) {
			redirect(user_url('login'));
		}
		
		$data= array();
		$data['user'] = $this->muser->get($this->muser->use_id);
		if(!$data['user']) die();
		
		
        $this->theme_data["main"] = "frontend/user/index";
        $this->template->view($this->theme_data, $data);
	}
	
	
	function favorites(){
		if (!$this->muser->checkLogin()) {
			redirect(user_url('login'));
		}
		$data= array();
		
		
		$this->theme_data["main"] = "frontend/user/favorites";
        $this->template->view($this->theme_data, $data);
	}
	
	function info($use_account = '') {
		$data= array();
		$data['user'] = $this->muser->get($use_account, 'use_account');
		$data['msg'] = '';
		$data['seo']['title']= 'Thông tin thành viên';
		if($data['user']){
			$data['seo']['title']= 'Thông tin thành viên '.$data['user']->use_account;
		}
		else {
			$data['msg'] = 'Thành viên không tồn tại.';
		}
		//$data['seo'] = $this->sseo->get('thong-tin-thanh-vien');
		
		$data['noindex'] = true;
		$this->theme_data["main"] = "frontend/user/info";
        $this->template->view($this->theme_data, $data);
	}
	
	function challenge() {
		
	}
	
	function reloaddata() {
		$userinfo = $this->muser->getLogin();
		$user = $this->muser->get($userinfo['use_id']);
		$this->muser->setLogin($user);
		die;
	}
	
	public function login() {
		if ($this->muser->checkLogin()) {
			$referer = $this->session->userdata('referrer');
			if ($referer) {
				$this->session->unset_userdata(array('referrer' =>''));
				redirect($referer, 'refresh');
				
			}
			redirect(user_url('index'));
		}

		$data = array();
		if ($this->input->post()) {
			$username = $this->input->post('username');
			$password = $this->input->post('password');
			if ($username && $password) {
				$user = $this->muser->get($username, "use_account");
				if (empty($user)) {
					$data['msg'] = "Tài khoản hoặc mật khẩu không đúng";
				}else if ($user->use_password == $this->muser->hash_pass($password)){
					unset($user->use_password);
					$this->muser->setLogin($user);
					var_dump($user);
					$data['msg'] = "Đăng nhập thành công!";
					echo '<meta http-equiv="refresh" content="5; url='.user_url('user/index').'">';
				}else {
					$data['msg'] = "Tài khoản hoặc mật khẩu không đúng";
				}
			}else {
				$data['msg'] = "Vui lòng điền đủ thông tin";
			}
		}

		$this->theme_data["main"] = "frontend/user/login";
		$data['seo'] = $this->sseo->get('dang-nhap');
		$this->template->view($this->theme_data, $data);
	}
	
	
	public function change() {
		$allow_change_field = array(
		'name', 'gender', 'avatar', 'job', 'phone', 'address'
		);
		if (!$this->input->is_ajax_request()) {
			exit('No direct script access allowed');
		}
		$type = $this->input->post("type");
		$data = $this->input->post("data");
		$key = '';
		switch($type){
			case 'fullname':
			$key = 'use_name';
			break;

			case 'job':
			$key = 'use_job';
			break;

			case 'preference':
			$key = 'use_preference';
			break;

			case 'phone':
			$key = 'use_phone';
			break;

			case 'addr':
			$key = 'use_address';
			break;

			case 'city':
			$key = 'use_city';
			break;
			
			case 'passwd':
			if($data != '')
				$this->muser->update_password($this->muser->use_id,$data);
			die("*****");
			break;
		}
		if($key != ''){
			$arr_update = array();
			$arr_update[$key] = $data;
			$this->muser->update($this->muser->use_id, 'use_id', $arr_update);
		
		}
		die($data);
	}
	function logout() {
		$this->load->library('user_agent');
		$this->muser->logout();
		if($this->agent->is_referral())
			redirect($this->agent->referrer());
		else
			redirect(base_url());
	}
	function upload(){
	//require('UploadHandler.php');
	require(APPPATH.'libraries/UploadHandler.php');
	 
	$upload_handler = new UploadHandler(array(
		'upload_dir'=> 'dataupload/user/avatar/',
		'upload_url'=> base_url().'dataupload/user/avatar/',
	));
	print_r($upload_handler);
	}
	
	public function do_upload() {
		if(!isset($_FILES['files']['name'])) return;
        $path_url =  'dataupload/user/avatar/';
		$this->load->model("simage");
		$this->load->model("sserver");
		$upload_path_url = base_url() . $path_url ;
		$this->load->helper('file');
        $config['upload_path'] = FCPATH . 'dataupload/user/avatar/';
        $config['allowed_types'] = 'jpg|jpeg|png|gif';
        $config['max_size'] = '30000';
        $config['max_width']  = '1024';
		$config['max_height']  = '768';
		$config['overwrite']  = true;
		$config['file_name']  = strtolower($this->muser->use_account).'.'.end(explode(".",$_FILES['files']['name']));
        $this->load->library('upload', $config);

        if (!$this->upload->do_upload('files')) {
             $error = array('error'=>true,'message' => $this->upload->display_errors('',''));
			  $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($error));
			// print_r( $error);
        } else {
            $data = $this->upload->data();
            
            // to re-size for thumbnail images un-comment and set path here and in json array
			
            $config = array();
            $config['image_library'] = 'gd2';
            $config['source_image'] = $data['full_path'];
           // $config['create_thumb'] = TRUE;
          // $config['new_image'] = $data['file_path'] . 'thumbs/';
		   if($data['image_width'] > 1024 || $data['image_height'] > 1024) {
		  if($data['image_width'] > 1024)
			$config['width'] = 1024; 
		if($data['image_height'] > 1024)
			$config['height'] = 1024;
           // $config['height'] = 50;
			$config['maintain_ratio'] = TRUE;
            $this->load->library('image_lib', $config);
            $this->image_lib->resize();
			}
			$this->muser->update($this->muser->use_id,'use_id', array('use_avatar'=>$path_url . $data['file_name']));
			$this->session->set_userdata(array('use_avatar'=>$path_url . $data['file_name']));
            //set the data for the json array
            $info = new StdClass;
            $info->name = $data['file_name'];
            $info->size = $data['file_size'] * 1024;
            $info->type = $data['file_type'];
            $info->url = image_thumbnail($path_url.$data['file_name'],'user-avatar-medium').'?v='.time();
           // $info->url = $upload_path_url . $data['file_name'];
            // I set this to original file since I did not create thumbs.  change to thumbnail directory if you do = $upload_path_url .'/thumbs' .$data['file_name']
            //$info->thumbnailUrl = $upload_path_url . 'thumbs/' . $data['file_name'];
			$this->simage->cache($path_url.$data['file_name']);
			$this->sserver->rsync();
           // $info->deleteUrl = base_url() . 'upload/deleteImage/' . $data['file_name'];
            $info->deleteType = 'DELETE';
            $info->error = null;

            $files[] = $info;
            //this is why we put this in the constants to pass only json data
            if ($this->input->is_ajax_request()) {
                echo json_encode(array("files" => $files,'error'=>false));
               
            } else {
                $file_data['upload_data'] = $this->upload->data();
                  
            }
        }
    }
    
	function lost_password(){
		$email = $this->input->post('email');
		if($email){
			$user = $this->muser->get($email, 'use_email');
			if($user){
				
			
			}
		}
		$data= array();
		$this->theme_data["main"] = "frontend/user/lost_password";
		$this->theme_data["right"] = null;
		$data['seo'] = $this->sseo->get('quen-mat-khau');
		$this->template->view($this->theme_data, $data);
	}
}
